import { defineStore } from "pinia"
import { RouteLocationNormalized } from "vue-router"

export interface TagView extends Partial<RouteLocationNormalized> {
  title?: string
}

export const useAppStore = defineStore("app", () => {
  const isCollapse = ref(false)
  const tagViewList = ref<TagView[]>([])

  // 设置菜单栏收缩展开
  function setIsCollapse() {
    isCollapse.value = !isCollapse
  }
  // 添加标签
  function addTagView(view: TagView) {
    if (tagViewList.value.some((item) => item.path === view.path)) {
      return false
    }
    if (view.meta && view.meta.affix) {
      tagViewList.value.unshift(Object.assign({}, view, { title: view.meta?.title || "no-name" }))
    } else {
      tagViewList.value.push(Object.assign({}, view, { title: view.meta?.title || "no-name" }))
    }
  }

  // 移除标签
  function removeTagView(view: TagView) {
    return new Promise((resolve) => {
      const newArr = tagViewList.value.filter((item) => item.path !== view.path)
      tagViewList.value = [...newArr]
      resolve({
        tagViewList: [...tagViewList.value]
      })
    })
  }
  // 移除其他
  function removeOther(view: TagView) {
    return new Promise((resolve) => {
      const newArr = tagViewList.value.filter((item) => item.path === view.path)
      tagViewList.value = [...newArr]
      resolve({
        tagViewList: [...tagViewList.value]
      })
    })
  }
  // 移除右边所有标签
  function removeRightOther(view: TagView) {
    return new Promise((resolve) => {
      let index = 0
      tagViewList.value.map((item, i) => {
        if (item.path === view.path) {
          index = i
        }
      })
      const newArr = tagViewList.value.filter((item, i) => i <= index)
      tagViewList.value = [...newArr]
      resolve({
        tagViewList: [...tagViewList.value]
      })
    })
  }
  // 移除所有标签
  function removeAll() {
    return new Promise((resolve) => {
      tagViewList.value = []
      resolve({
        tagViewList: [...tagViewList.value]
      })
    })
  }
  return {
    isCollapse,
    tagViewList,
    addTagView,
    removeTagView,
    setIsCollapse,
    removeOther,
    removeRightOther,
    removeAll
  }
})
